const Topic = require('../models/topics')
const User = require('../models/users')
const Question = require('../models/questions')
class TopicsCtl {
  // 检查话题是否存在中间件
  async checkTopicExist(ctx, next) {
    const topic = await Topic.findById(ctx.params.id)
    if (!topic) {
      ctx.throw(404, '该话题不存在')
    }
    await next()
  }
  // 获取话题列表
  async find(ctx) {
    const { per_page = 10 } = ctx.query
    // 当前页
    const page = Math.max(ctx.query.page * 1, 1) - 1
    // 每页显示多少条，同时防止小于1的情况
    const perPage = Math.max(per_page * 1, 1)
    ctx.body = await Topic.find({ name: new RegExp(ctx.query.q) })
      .limit(perPage)
      .skip(page * perPage)
  }
  // 获取指定话题
  async findById(ctx) {
    const { fields = '' } = ctx.query
    const selectedFields = fields
      .split(';')
      .filter(v => v)
      .map(v => ' +' + v)
      .join('')
    const topic = await Topic.findById(ctx.params.id).select(selectedFields)
    ctx.body = topic
  }
  // 新建话题
  async create(ctx) {
    ctx.verifyParams({
      name: { type: 'string', required: true },
      avatar_url: { type: 'string', required: false },
      introduction: { type: 'string', required: false }
    })
    const topic = await new Topic(ctx.request.body).save()
    ctx.body = topic
  }
  // 修改指定话题
  async update(ctx) {
    ctx.verifyParams({
      name: { type: 'string', required: false },
      avatar_url: { type: 'string', required: false },
      introduction: { type: 'string', required: false }
    })
    const topic = await Topic.findByIdAndUpdate(ctx.params.id, ctx.request.body)
    ctx.body = topic
  }
  // 获取某个话题的关注用户列表
  async listTopicsFollowers(ctx) {
    const users = await User.find({ followingTopics: ctx.params.id })
    ctx.body = users
  }
  // 获取某个话题下的问题列表
  async listQuestions(ctx) {
    const questions = await Question.find({ topics: ctx.params.id })
    ctx.body = questions
  }
}
module.exports = new TopicsCtl()
